const express = require('express');
const router = express.Router();
const { authenticateToken, isAdmin } = require('../middleware/auth');
const { cleanupUnusedImages, getUploadsStats } = require('../utils/fileCleanup');
const { User, AIRole, ApiKey, SharedImage, Interaction, UserLike } = require('../models');
const sequelize = require('../config/db');

// 获取uploads目录统计信息
router.get('/uploads/stats', authenticateToken, isAdmin, async (req, res) => {
  try {
    const stats = await getUploadsStats();
    res.json({
      success: true,
      data: {
        ...stats,
        totalSizeMB: (stats.totalSize / (1024 * 1024)).toFixed(2)
      }
    });
  } catch (error) {
    console.error('获取uploads统计信息失败:', error);
    res.status(500).json({ 
      success: false, 
      error: '获取统计信息失败',
      message: error.message 
    });
  }
});

// 预览清理结果（不实际删除）
router.get('/uploads/cleanup/preview', authenticateToken, isAdmin, async (req, res) => {
  try {
    const results = await cleanupUnusedImages(true); // dryRun = true
    res.json({
      success: true,
      data: {
        ...results,
        message: `发现 ${results.unusedFiles.length} 个未使用的文件，总共 ${results.totalFiles} 个文件`
      }
    });
  } catch (error) {
    console.error('预览清理结果失败:', error);
    res.status(500).json({ 
      success: false, 
      error: '预览清理结果失败',
      message: error.message 
    });
  }
});

// 执行文件清理
router.post('/uploads/cleanup', authenticateToken, isAdmin, async (req, res) => {
  try {
    const results = await cleanupUnusedImages(false); // dryRun = false
    res.json({
      success: true,
      data: {
        ...results,
        message: `成功删除 ${results.deletedFiles.length} 个未使用的文件`
      }
    });
  } catch (error) {
    console.error('执行文件清理失败:', error);
    res.status(500).json({ 
      success: false, 
      error: '执行文件清理失败',
      message: error.message 
    });
  }
});

// 导出数据
router.post('/export-data', authenticateToken, isAdmin, async (req, res) => {
  try {
    const { tables, format } = req.body;
    
    if (!tables || !Array.isArray(tables) || tables.length === 0) {
      return res.status(400).json({
        success: false,
        error: '请选择要导出的数据表'
      });
    }
    
    const modelMap = {
      'Users': User,
      'AIRoles': AIRole,
      'ApiKeys': ApiKey,
      'SharedImages': SharedImage,
      'Interactions': Interaction,
      'UserLikes': UserLike
    };
    
    let exportData = {};
    
    // 获取每个表的数据
    for (const tableName of tables) {
      if (modelMap[tableName]) {
        const data = await modelMap[tableName].findAll({
          raw: true,
          nest: false
        });
        exportData[tableName] = data;
      }
    }
    
    let result = '';
    
    if (format === 'json') {
      result = JSON.stringify(exportData, null, 2);
    } else if (format === 'sql') {
      result = generateSQLInserts(exportData);
    }
    
    res.json({
      success: true,
      data: result
    });
    
  } catch (error) {
    console.error('导出数据失败:', error);
    res.status(500).json({
      success: false,
      error: '导出数据失败',
      message: error.message
    });
  }
});

// 导出表结构
router.post('/export-schema', authenticateToken, isAdmin, async (req, res) => {
  try {
    const { tables } = req.body;
    
    if (!tables || !Array.isArray(tables) || tables.length === 0) {
      return res.status(400).json({
        success: false,
        error: '请选择要导出的数据表'
      });
    }
    
    let schemaSQL = '';
    
    for (const tableName of tables) {
      try {
        const [results] = await sequelize.query(`SHOW CREATE TABLE ${tableName}`);
        if (results && results.length > 0) {
          schemaSQL += `-- 表结构: ${tableName}\n`;
          schemaSQL += `DROP TABLE IF EXISTS \`${tableName}\`;\n`;
          schemaSQL += results[0]['Create Table'] + ';\n\n';
        }
      } catch (tableError) {
        console.warn(`获取表 ${tableName} 结构失败:`, tableError.message);
        schemaSQL += `-- 警告: 无法获取表 ${tableName} 的结构\n\n`;
      }
    }
    
    res.json({
      success: true,
      data: schemaSQL
    });
    
  } catch (error) {
    console.error('导出表结构失败:', error);
    res.status(500).json({
      success: false,
      error: '导出表结构失败',
      message: error.message
    });
  }
});

// 生成SQL插入语句
function generateSQLInserts(data) {
  let sql = '';
  
  for (const [tableName, records] of Object.entries(data)) {
    if (records && records.length > 0) {
      sql += `-- 数据插入: ${tableName}\n`;
      
      const columns = Object.keys(records[0]);
      const columnNames = columns.map(col => `\`${col}\``).join(', ');
      
      for (const record of records) {
        const values = columns.map(col => {
          const value = record[col];
          if (value === null || value === undefined) {
            return 'NULL';
          } else if (typeof value === 'string') {
            return `'${value.replace(/'/g, "''")}'`;
          } else if (value instanceof Date) {
            return `'${value.toISOString().slice(0, 19).replace('T', ' ')}'`;
          } else {
            return value;
          }
        }).join(', ');
        
        sql += `INSERT INTO \`${tableName}\` (${columnNames}) VALUES (${values});\n`;
      }
      
      sql += '\n';
    }
  }
  
  return sql;
}

module.exports = router;